package com.czy.owner.ui.coupons;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.GetCouponsCenterAdapter;
import com.czy.owner.api.OwnerCouPonsGroupReceiveApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.GetCouponsCenterModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.login.LoginActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.widget.guidehelp.GuideHelper;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.List;

import butterknife.BindView;


/**
 * Created by wangyang on 2017/4/13 0013.
 * 领券中心
 */

public class GetCouponsCenterActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.easy_recycleview)
    EasyRecyclerView recyclerView;
    private GetCouponsCenterAdapter adapter = null;
    private Handler handler = new Handler();
    private int page = 1;
    private boolean isPlatform;

    @Override
    protected int attachLayoutRes() {
        return R.layout.common_activity_easyrecycleview;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        RxBus.getDefault().register(this);
        getToolbarTitle().setText(R.string.get_coupon_center);
        isPlatform = getIntent().getBooleanExtra("isPlatform",false);
        recyclerView.setLayoutManager(new LinearLayoutManager(GetCouponsCenterActivity.this));
        recyclerView.setAdapterWithProgress(adapter = new GetCouponsCenterAdapter(GetCouponsCenterActivity.this));
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore, new RecyclerArrayAdapter.OnNoMoreListener() {
            @Override
            public void onNoMoreShow() {
                // adapter.resumeMore();
            }

            @Override
            public void onNoMoreClick() {
                adapter.resumeMore();
            }
        });

        adapter.setError(R.layout.view_error_net, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();

            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();

            }
        });
        adapter.setCouponsOnClick(new GetCouponsCenterAdapter.OnGetCouponsListener() {
            @Override
            public void getCouponsOnClick(final GetCouponsCenterModel.ListBean model, final int position) {
                if (UserHelper.getInstance().isLogined()) {
                    //  2017-12-12 wyang 修改
                    int storeId = (int) SharedPreferencesUtils.getParam(GetCouponsCenterActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0);
                    String needBind = model.getNeedBind();
                    if (storeId != 0) {  //已绑定
                        getCoupons(model,position);
                    } else {
                        //  未绑定 需要绑定领取进入门店弹窗绑定
                        if (needBind.equals("true")) {
                            final GuideHelper guideHelper = new GuideHelper(GetCouponsCenterActivity.this);
                            View view = guideHelper.inflate(R.layout.custom_get_coupons_view);
                            Button btnCanel = (Button) view.findViewById(R.id.btn_cancel);
                            Button btnSure = (Button) view.findViewById(R.id.btn_sure);
                            ImageView imgClose = (ImageView) view.findViewById(R.id.img_close);
                            btnCanel.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    guideHelper.dismiss();
                                }
                            });
                            btnSure.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    RxBus.getDefault().post(Constants.RXBUS_CODE_SWITCH_MAIN_TAB, new CommonEvent("登录未绑定"));
                                    finish();
                                    guideHelper.dismiss();
                                }
                            });
                            imgClose.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    guideHelper.dismiss();
                                }
                            });

                            GuideHelper.TipData tipDataCustom = new GuideHelper.TipData(view, Gravity.CENTER);
                            guideHelper.addPage(false, tipDataCustom);
                            guideHelper.show(false);
                        }else {
                            getCoupons(model,position);
                        }
                    }


                } else {
                     startActivity(new Intent(GetCouponsCenterActivity.this, LoginActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, false));

                }
            }
        });


        recyclerView.setRefreshListener(this);
        onRefresh();
    }

    @Override
    protected void updateViews() {

    }


    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(GetCouponsCenterActivity.this)) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page++;
                getDataList();

            }
        }, 1000);
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                adapter.clear();
                page = 1;
                getDataList();
            }
        }, 1000);
    }



    private void getCoupons(final GetCouponsCenterModel.ListBean model,final int position){
        String url = Constants.APP_API_BASE + Constants.OWN_RECEIVECOUPONS;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(GetCouponsCenterActivity.this).getSession());
        params.addBodyParameter("couponsGroupId", model.getCouponsGroupId() + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                if (flag) {
                    PhoneUtils.ShowToastMessage(GetCouponsCenterActivity.this, "领取成功");
                    if (model.getTotalCount() == 1) {
                        adapter.remove(position);
                        adapter.notifyDataSetChanged();
                    } else {
                        model.setTotalCount(model.getTotalCount() - 1);
                    }

                } else {
                    PhoneUtils.ShowToastMessage(GetCouponsCenterActivity.this, exp);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getDataList() {
        OwnerCouPonsGroupReceiveApi ownerCouPonsGroupReceiveApi = new OwnerCouPonsGroupReceiveApi(new HttpOnNextListener<GetCouponsCenterModel>() {
            @Override
            public void onNext(GetCouponsCenterModel model) {
                setDataList(model.getList());
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
//                Gson gson = new Gson();
//                Type type = new TypeToken<BaseResultEntity<GetCouponsCenterModel>>() {
//                }.getType();
//                BaseResultEntity<GetCouponsCenterModel> cacheList = gson.fromJson(cache, type);
//                setDataList(cacheList.getData().getList());

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(GetCouponsCenterActivity.this, e.getMessage());
            }
        }, this, page + "");

        //ownerCouPonsGroupReceiveApi.setSession(UserHelper.getInstance().getSessionInfoModel(GetCouponsCenterActivity.this).getSession());
        if(isPlatform){
            ownerCouPonsGroupReceiveApi.setStoreId("0");
        }else {
            ownerCouPonsGroupReceiveApi.setStoreId(SharedPreferencesUtils.getParam(GetCouponsCenterActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        }
        ownerCouPonsGroupReceiveApi.setSession(UserHelper.getInstance().getSession(GetCouponsCenterActivity.this));
        ownerCouPonsGroupReceiveApi.setPage(page + "");
        ownerCouPonsGroupReceiveApi.setSize("10");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(ownerCouPonsGroupReceiveApi);
    }


    private void setDataList(List<GetCouponsCenterModel.ListBean> list) {
        if (list.size() < 9) {
            adapter.stopMore();
        }
        adapter.addAll(list);
        if (adapter.getAllData().size() == 0) {
            recyclerView.setEmptyView(R.layout.view_empty_common);
            recyclerView.showEmpty();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }

    @Subscribe(code = Constants.GET_COUPONS_SUCCESS, threadMode = ThreadMode.MAIN)
    public void getCouPonsSuccess(CommonEvent event) {
        onRefresh();
    }

}
